<template>
  <div>
    <h1>管理员列表</h1>
    <el-table :data="adminList" style="width: 100%" empty-text="亲，没有数据哦！" stripe v-loading="loading" >
      <el-table-column prop="adminid" label="管理员编号" width="400" align="center" />
      <el-table-column prop="adminname" label="姓名" width="180" align="center"/>
      <el-table-column prop="role" label="角色" width="180" align="center">
        <template #default="scope">
          <span>{{ scope.row.role == 1 ? "超级管理员" : "普通管理员" }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-popconfirm title="亲，您真的要删除吗?" @confirm="deleteAdmin(scope.row.adminid)">
            <template #reference>
              <el-button  v-if="crud.charAt(3) === '1'">删除</el-button>
            </template>
          </el-popconfirm>
          <el-button @click="editShowFn(scope.row.adminname)"  v-if="crud.charAt(2) === '1'" >修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Edit :adminname="editAdminName" v-show="isShowEdit" @hide="hideFn" @updatesuccess="saveFn"></Edit>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import "element-plus/dist/index.css";
import { reactive ,ref} from "vue";
import service from "../../../utils/service";
import Edit from "./Edit.vue";
import {useRoute} from "vue-router"

const $route = useRoute()
const crud:string = ($route.meta.crud as string)
console.log("$route",$route);

const loading = ref(true)

interface IAdmin {
  adminname: string;
  password: string;
  role: number; //1：超管 2：普通管理员
  adminid: string;
  checkedKeys: string[];
}

const adminList = reactive<IAdmin[]>([]);

//1、获取管理员信息
const getAdminList = () => {
  service({
    url: "/admin/list",
  }).then((res) => {
    if (res.data.code === "200") {
      adminList.length = 0;
      adminList.push(...res.data.data);
      loading.value = false
    }
  });
};

getAdminList();

//2、删除管理员
const deleteAdmin = (adminid: string) => {
  service({
    url: "/admin/delete",
    method: "post",
    data: {
      adminid,
    }
  }).then((res) => {
    if (res.data.code === "200") {
      ElMessage({
        message: "删除成功！",
        type: "success",
      });
      getAdminList();
    }
  });
};

//修改相关代码
const isShowEdit = ref(false)//控制修改元素的显示和隐藏
const editAdminName = ref("")//要修改的 管理员姓名


const editShowFn = (adminname:string) =>{
    editAdminName.value = adminname
    isShowEdit.value = true
}

//隐藏弹出框
const hideFn = () =>{
    isShowEdit.value = false
}

const saveFn = () =>getAdminList();


</script>

<style>
</style>